package com.wngbms.netty.seatdemo.server;

import com.wngbms.netty.seatdemo.comm.*;
import com.wngbms.netty.seatdemo.message.BaseHeader;
import com.wngbms.netty.seatdemo.message.SeatInMessage;
import com.wngbms.netty.seatdemo.service.HandleFactory;
import com.wngbms.netty.seatdemo.service.SeatTypeHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SeatBizHandler extends SimpleChannelInboundHandler<SeatInMessage> {

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static final Map<String, Channel> USER_CHANNEL_MAP = new ConcurrentHashMap<>();
    public static final Map<SocketAddress, String> USER_SOCKET_MAP = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SeatInMessage msg) throws Exception {
        byte[] body = msg.getBody();
        BaseHeader baseHeader = msg.getBaseHeader();
//        log.info("baseHeader:{}", baseHeader.hashCode());
//        if (body != null) {
//            log.info("{}", new String(body, StandardCharsets.UTF_8));
//        }

        msg.setChannelHandlerContext(ctx);
        executorService.submit(() -> {
            CmdType cmdType = baseHeader.getCmdType();
//            log.info("doHandle:{}", cmdType);
            SeatTypeHandler seatTypeHandler = HandleFactory.getHandler(cmdType);
            seatTypeHandler.handleInbound(msg);
        });
    }
}
